﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace T.FAS.Runtime.Metadata.Entity
{
    /// <summary>
    /// 枚举
    /// </summary>
    public class EnumUtil
    {
        /// <summary>
        /// 获取枚举描述信息
        /// </summary>
        /// <param name="enumValue">枚举值</param>
        /// <param name="nameInstend">当枚举没有定义Description，是否用枚举名代替，默认为true</param>
        /// <returns></returns>
        public static string GetDescription(System.Enum enumValue, bool nameInstend = true)
        {
            if (enumValue == null)
            {
                return string.Empty;
            }

            Type type = enumValue.GetType();
            string name = Enum.GetName(type, enumValue);
            if (string.IsNullOrEmpty(name))
            {
                return string.Empty;
            }

            FieldInfo fieldInfo = type.GetField(name);
            DescriptionAttribute attribute = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attribute == null && nameInstend == true)
            {
                return name;
            }
            return attribute == null ? string.Empty : attribute.Description;
        }
    }
}
